<?php

class Doctrine_Template_MoreTimestampable extends Doctrine_Template_Timestampable
{
  protected $_suffix = '_at',
            $_prefix = 'is_';

  protected $_conf = array('name'         =>  null,
                          'alias'         =>  null,
                          'type'          =>  'timestamp',
                          'format'        =>  'Y-m-d H:i:s',
                          'disabled'      =>  false,
                          'expression'    =>  false,
                          'options'       =>  array('notnull' => false),
                          'link'          =>  array());

  protected $_link = array('name'         =>  null,
                          'alias'         =>  null,
                          'type'          =>  'boolean',
                          'format'        =>  null,
                          'disabled'      =>  false,
                          'expression'    =>  false,
                          'options'       =>  array('notnull' => false));

  public function setTableDefinition()
  {
    parent::setTableDefinition();
    $this->_mergeOptions();
    foreach($this->_options as $option => $datas)
    {
      if($option != "updated" && $option != "created")
      {
        $options = $this->_options[$option];
        $name = $options['name'];
        if ($options['alias']) {
            $name .= ' as ' . $options['alias'];
        }
        $this->hasColumn($name, $options['type'], null, $options['options']);
        $this->_addLinkField($option);
      }
    }
    $this->addListener(new Doctrine_Template_Listener_MoreTimestampable($this->_options));
  }

  protected function _addLinkField($option)
  {
    if($this->_options[$option]['link'] == array())
    {
      $this->_options[$option]['link'] = $this->_link;
    }
    else
    {
      $this->_options[$option]['link'] = array_merge($this->_link, $this->_options[$option]['link']);
    }
    if(is_null($this->_options[$option]['link']['name']))
    {
      $this->_options[$option]['link']['name'] = $this->_prefix.$option;
    }
    $this->hasColumn($this->_options[$option]['link']['name'],
                    $this->_options[$option]['link']['type'],
                    null,
                    $this->_options[$option]['link']['options']
    );
  }

  protected function _mergeOptions()
  {
    foreach($this->_options as $option => $datas)
    {
      if($option != "updated" && $option != "created")
      {
        if(is_array($this->_options[$option]))
        {
          $this->_options[$option] = array_merge($this->_conf, $this->_options[$option]);
        }
        else
        {
          $this->_options[$option] = $this->_conf;
        }
        if(is_null($this->_options[$option]['name']))
        {
          $this->_options[$option]['name'] = $option.$this->_suffix;
        }
      }
    }
  }
}